package main

import (
	"backend/Handlers"
	"backend/Service/SQL/MySQL"
	"encoding/json"
	"fmt"
	"os"
)

type Config struct {
	Addr                 string `json:"addr"`
	Home_page            string `json:"home_page"`
	Temp_path            string `json:"temp_path"`
	HttpTimeOut          int    `json:"http_timeout"`
	Max_upload_file_size struct {
		Unit string `json:"unit"`
		Num  int64  `json:"num"`
		Size int64  `json:"-"`
	}
	Static struct {
		Dir  map[string]string `json:"dir"`
		File map[string]string `json:"file"`
	}
	Database struct {
		SQL struct {
			Mysql struct {
				Addr    string `json:"addr"`
				Account string `json:"account"`
				Dbname  string `json:"dbname"`
			}
		}
	}
}

var GlobalConfig Config

func init() {
	// 获取配置
	fmt.Println("init config...")
	fmt.Println("open config.json...")
	data, err := os.ReadFile("./config.json")
	if err != nil {
		fmt.Println("open config_default.json...")
		data, err = os.ReadFile("./config_default.json")
		if err != nil {
			panic(err)
		}
	}
	err = json.Unmarshal(data, &GlobalConfig)
	if err != nil {
		panic(err)
	}
	if GlobalConfig.Max_upload_file_size.Unit == "G" {
		GlobalConfig.Max_upload_file_size.Size = GlobalConfig.Max_upload_file_size.Num << 30
	}
	if GlobalConfig.Max_upload_file_size.Unit == "M" {
		GlobalConfig.Max_upload_file_size.Size = GlobalConfig.Max_upload_file_size.Num << 20
	}
	if GlobalConfig.Max_upload_file_size.Unit == "K" {
		GlobalConfig.Max_upload_file_size.Size = GlobalConfig.Max_upload_file_size.Num << 10
	}

	Handlers.HTTP_TIMEOUT = GlobalConfig.HttpTimeOut
	Handlers.FILE_UPLOAD_SIZE = GlobalConfig.Max_upload_file_size.Size

	// 初始化数据库
	MySQL.Init(
		GlobalConfig.Database.SQL.Mysql.Dbname,
		GlobalConfig.Database.SQL.Mysql.Account,
		GlobalConfig.Database.SQL.Mysql.Addr)
}
